package com.ruoyi.system.im;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.TencentCloudImApiEnum;
import com.ruoyi.common.utils.HttpClientUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ImAppInfoVo;
import com.tencentyun.TLSSigAPIv2;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class TencentCloudImUtil {
    private static final String HTTPS_URL_PREFIX = "https://adminapisgp.im.qcloud.com/";
    private static final String APP_MANAGER = "administrator";
    private static final String REDIS_IM_USER_SIG = "silence:im_user_sig:";

    @Value("${IMConfig.sdkAppId}")
    private long sdkAppId;
    @Value("${IMConfig.secretKey}")
    private String secretKey;



//    @Autowired
//    private Cache cache;

    /**
     * 获取腾讯云用户签名
     */
    public String getTxCloudUserSig() {
//        String userSig = (String) cache.get(REDIS_IM_USER_SIG + APP_MANAGER);
//        if (StringUtils.isEmpty(userSig)) {
            TLSSigAPIv2 tlsSigApi = new TLSSigAPIv2(sdkAppId, secretKey);
            String userSig = tlsSigApi.genUserSig(APP_MANAGER, 86400);
//            cache.put(REDIS_IM_USER_SIG + APP_MANAGER, userSig, 86400L);
//        }
        return userSig;
    }


    public String getUserSig(String userId) {
//        String userSig = (String) cache.get(REDIS_IM_USER_SIG + APP_MANAGER);
//        if (StringUtils.isEmpty(userSig)) {
        TLSSigAPIv2 tlsSigApi = new TLSSigAPIv2(sdkAppId, secretKey);
        String userSig = tlsSigApi.genUserSig(userId, 86400);
//            cache.put(REDIS_IM_USER_SIG + APP_MANAGER, userSig, 86400L);
//        }
        return userSig;
    }
    /**
     * 获取腾讯im请求路径
     */
    private String getHttpsUrl(String imServiceApi, Integer random) {
        return String.format("%s%s?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json",
                HTTPS_URL_PREFIX, imServiceApi, sdkAppId, APP_MANAGER, this.getTxCloudUserSig(), random);
    }

    /**
     * 导入单个账号
     *
     * @param userId 用户id
     */
    public String accountImport(String userId) {
        return accountImport(userId, null);
    }

    public String accountImport(String userId, String userName) {
        return accountImport(userId, userName, null);
    }

    public String  accountImport(String userId, String userName, String faceUrl) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ACCOUNT_IMPORT.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
//        Map<String,String> map=new HashMap<>();
        jsonObject.put("Identifier", userId);
        if (StringUtils.isNotEmpty(userName)) {
            jsonObject.put("Nick", userName);
        }
        if (StringUtils.isNotEmpty(faceUrl)) {
            jsonObject.put("FaceUrl", faceUrl);
        }
        log.info("腾讯云im导入单个账号，请求参数：{}", jsonObject);
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im导入单个账号，返回结果：{}", result);
        return result;
    }

 
//    /**
//     * 导入多个账号
//     * @param userIds 用户id集合
//     */
//    public void multiAccountImport(List<String> userIds) {
//        Integer random = RandomUtils.nextInt(0, 999999999);
//        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.MULTI_ACCOUNT_IMPORT.getUrl(), random);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("Accounts", userIds);
//        log.info("腾讯云im导入多个账号，请求参数：{}", jsonObject.toString());
//        String result = HttpClientUtil.doPost(httpsUrl, jsonObject);
//        log.info("腾讯云im导入单个账户，返回结果：{}", result);
//    }
//
//    /**
//     * 批量删除账号
//     * @param userIds 用户id集合
//     */
//    public void accountDeleteBatch(List<String> userIds) {
//        Integer random = RandomUtils.nextInt(0, 999999999);
//        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ACCOUNT_DELETE.getUrl(), random);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("DeleteItem", getUserIdJsonList(userIds));
//        log.info("腾讯云im删除账号，请求参数：{}", jsonObject.toString());
//        String result = HttpClientUtil.doPost(httpsUrl, jsonObject);
//        log.info("腾讯云im删除账户，返回结果：{}", result);
//    }
//
    /**
     * 查询账号是否已经导入im
     * @param userIds 用户id集合
     */
    public String accountCheck(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ACCOUNT_CHECK.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("CheckItem", getUserIdJsonList(userIds));
        log.info("腾讯云im查询账号，请求参数：{}", jsonObject.toString());
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im查询账号，返回结果：{}", result);
        return result;
    }

    private List<JSONObject> getUserIdJsonList(List<String> userIds) {
        return userIds.stream().map(v -> {
            JSONObject userIdJson = new JSONObject();
            userIdJson.put("UserID", v);
            return userIdJson;
        }).collect(Collectors.toList());
    }

    /**
     * 获取用户的好友数量
     * @param userId
     * @return
     */
    public Integer getUserFriendNum(String userId){
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.FRIEND_GET.getUrl(), random);
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("From_Account",userId);
        jsonObject.put("StartIndex",0);
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im拉取好友，返回结果：{}", result);
        Map map = JSON.parseObject(result, Map.class);
        Integer friendNum = (Integer) map.get("FriendNum");
        return friendNum;
    }

    /**
     * 获取用户加的群组数量
     * @param userId
     * @return
     */
    public Integer getUserGroupNum(String userId){
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.GET_JOINED_GROUP_LIST.getUrl(), random);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("Member_Account",userId);
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im拉取用户群组，返回结果：{}", result);
        Map map = JSON.parseObject(result, Map.class);
        Integer friendNum = (Integer) map.get("TotalCount");
        return friendNum;
    }

    public Boolean deleteUser(String userId){
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ACCOUNT_DELETE.getUrl(), random);
        JSONObject jsonObject=new JSONObject();
        List<String> userIdList=new ArrayList<>();
        userIdList.add(userId);
        List<JSONObject> userIdJsonList = getUserIdJsonList(userIdList);
        jsonObject.put("DeleteItem",userIdJsonList);
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im拉取用户群组，返回结果：{}", result);
        Map map = JSON.parseObject(result, Map.class);
        if ((Integer) map.get("ErrorCode")==0){
            return true;
        }else {
            return false;
        }
    }

        /**
     * 查询单聊消息
     * @param fromUserId 发送方用户id
     * @param toUserId 接收方用户id
     * @param maxCnt 查询条数
     * @param startTime 起始时间（单位：秒）
     * @param endTime 结束时间（单位：秒）
     * @param lastMsgKey 最后一条消息的 MsgKey
     * @return 单聊消息列表
     */
    public String adminGetRoamMsg(String fromUserId, String toUserId, Integer maxCnt, Long startTime, Long endTime, String lastMsgKey) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.ADMIN_GET_ROAM_MSG.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", fromUserId);
        jsonObject.put("To_Account", toUserId);
        jsonObject.put("MaxCnt", maxCnt);
        jsonObject.put("MinTime", startTime);
        jsonObject.put("MaxTime", endTime);
        if (StringUtils.isNotEmpty(lastMsgKey)){
            jsonObject.put("LastMsgKey", lastMsgKey);
        }
        log.info("腾讯云im查询单聊消息，请求参数：{}", jsonObject.toString());
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im查询单聊消息，返回结果：{}", result);
        return result;
    }



    /**
     * 单发单聊消息
     * @param syncOtherMachine 是否同步消息到发送方（1-同步，2-不同步）
     * @param fromUserId 发送方用户id
     * @param toUserId 接收方用户id
     * @param msgType 消息对象类型
     * @param msgContent 消息内容
     */
    public String sendMsg(Integer syncOtherMachine, String fromUserId, String toUserId, String msgType, String msgContent) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.SEND_MSG.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("SyncOtherMachine", syncOtherMachine);
        if (StringUtils.isNotEmpty(fromUserId)) {
            // 发送方不为空表示指定发送用户，为空表示为管理员发送消息
            jsonObject.put("From_Account", fromUserId);
        }
        jsonObject.put("To_Account", toUserId);
        jsonObject.put("MsgRandom", random);
        List<JSONObject> msgBody = getMsgBody("TIMTextElem", msgContent);
        jsonObject.put("MsgBody", msgBody);
        log.info("腾讯云im单发单聊消息，请求参数：{}", jsonObject.toString());
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im单发单聊消息，返回结果：{}", result);
        return result;
    }
 
 
    /**
     * 拼接发送消息内容
     * @param msgType 消息类型
     * @param msgContent 发送消息内容
     * @return 消息内容
     */
    private List<JSONObject> getMsgBody(String msgType, String msgContent) {
        List<JSONObject> msgBody = new ArrayList<>();
        if (msgType.equals("TIMTextElem")) {
            // 文本类型
            JSONObject msgBodyJson = new JSONObject();
            msgBodyJson.put("MsgType", msgType);
            JSONObject msgContentObj = new JSONObject();
            msgContentObj.put("Text", msgContent);
            msgBodyJson.put("MsgContent", msgContentObj);
            msgBody.add(msgBodyJson);
        }
        return msgBody;
    }

    /**
     * 获取用户的好友列表
     * @param userId
     * @return
     */
    public List<String> getUserFriendList(String userId){
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.FRIEND_GET.getUrl(), random);
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("From_Account",userId);
        jsonObject.put("StartIndex",0);
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im拉取好友列表，返回结果：{}", result);
        Map map = JSON.parseObject(result, Map.class);
//        Integer friendNum = (Integer) map.get("FriendNum");
        List<String> userIDList=new ArrayList<>();
        List<Map> userDataItem = (List<Map>) map.get("UserDataItem");

        if (ObjectUtils.isNotEmpty(userDataItem) && !userDataItem.isEmpty()) {
            for (Map user : userDataItem) {
                String toAccount = (String) user.get("To_Account");
                userIDList.add(toAccount);
            }
        }
        return userIDList;
    }

    /**
     * 新增群组
     * @param ownerId 群主id
     * @param name 群名称
     * @param userIds 群成员id
     * @return
     */
    public String addGroup(String ownerId,String name,List<String> userIds){
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.CREATE_GROUP.getUrl(), random);
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("Owner_Account",ownerId);
        jsonObject.put("Type","Public");
        jsonObject.put("Name",name);
        List<JSONObject> groupUserId = getGroupUserId(userIds);
        jsonObject.put("MemberList",groupUserId);
        log.info("腾讯云im新增群组，请求参数：{}", jsonObject.toString());
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云建立群组，返回结果：{}", result);
        Map map = JSON.parseObject(result, Map.class);
        if ((Integer) map.get("ErrorCode")==0){
            return (String) map.get("GroupId");
        }else {
            return null;
        }
    }

    private List<JSONObject> getGroupUserId(List<String> userIds) {
        return userIds.stream().map(v -> {
            JSONObject userIdJson = new JSONObject();
            userIdJson.put("Member_Account", v);
            return userIdJson;
        }).collect(Collectors.toList());
    }


    /**
     * 群组详情
     * @param groupId
     * @return
     */
    public Map groupDetail(String groupId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.GET_GROUP_INFO.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
        List<String> groupIdList = new ArrayList<>();
        groupIdList.add(groupId);
        jsonObject.put("GroupIdList", groupIdList);
        //指定字段
        JSONObject object = new JSONObject();
        //基础字段
        List<String> baseList = new ArrayList<>();
        baseList.add("Name");
        baseList.add("Introduction");
        object.put("GroupBaseInfoFilter", baseList);
        jsonObject.put("ResponseFilter", object);
        log.info("腾讯云im获取群组资料，请求参数：{}", jsonObject.toString());
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im获取群组资料，返回结果：{}", result);
        Map map = JSON.parseObject(result, Map.class);
        List groupInfo = (List) map.get("GroupInfo");
        Map info = (Map) groupInfo.get(0);
        return info;
    }

    /**
     * 修改群组资料
     * @param groupId
     * @param name
     * @param introduction
     * @return
     */
    public Boolean update(String groupId,String name,String introduction){
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.MODIFY_GROUP_BASE_INFO.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId",groupId);
        jsonObject.put("Name",name);
        jsonObject.put("Introduction",introduction);
        log.info("腾讯云im修改群组资料，请求参数：{}", jsonObject.toString());
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im修改群组资料，返回结果：{}", result);
        Map map = JSON.parseObject(result, Map.class);
        if ((Integer) map.get("ErrorCode")==0){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 群组成员列表
     * @param groupId
     * @return
     */
    public List<Map> groupUserList(String groupId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.GET_GROUP_INFO.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
        List<String> groupIdList = new ArrayList<>();
        groupIdList.add(groupId);
        jsonObject.put("GroupIdList", groupIdList);
        JSONObject object = new JSONObject();
        //基础字段
        List<String> baseList = new ArrayList<>();
        baseList.add("Account");
        baseList.add("Role");
        baseList.add("JoinTime");
        object.put("MemberInfoFilter", baseList);

        jsonObject.put("ResponseFilter", object);
        log.info("腾讯云im获取群组资料，请求参数：{}", jsonObject.toString());
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im获取群组资料，返回结果：{}", result);
        Map map = JSON.parseObject(result, Map.class);
        List groupInfo = (List) map.get("GroupInfo");
        Map info = (Map) groupInfo.get(0);
        List<Map> userList = (List<Map>) info.get("MemberList");
        return userList;
    }

    public boolean deleteGroup(String groupId){
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.DESTROY_GROUP.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId",groupId);
        log.info("腾讯云im解散群，请求参数：{}", jsonObject.toString());
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im解散群，返回结果：{}", result);
        Map map = JSON.parseObject(result, Map.class);
        if ((Integer) map.get("ErrorCode")==0){
            return true;
        }else {
            return false;
        }
    }

    public Boolean deleteGroupUser(String groupId,List<String> groupUserIds){
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.DELETE_GROUP_MEMBER.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId",groupId);
        jsonObject.put("MemberToDel_Account",groupUserIds);
        log.info("腾讯云im删除群成员，请求参数：{}", jsonObject.toString());
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im删除群成员，返回结果：{}", result);
        Map map = JSON.parseObject(result, Map.class);
        if ((Integer) map.get("ErrorCode")==0){
            return true;
        }else {
            return false;
        }

    }

    public void deleteUserContact(String userId,List<String> userFriendIds) {
        for (String friendId : userFriendIds) {
            Integer random = RandomUtils.nextInt(0, 999999999);
            String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.CONTACT_DELETE.getUrl(), random);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("From_Account",userId);
            jsonObject.put("Type",1);
            jsonObject.put("To_Account",friendId);
            jsonObject.put("ClearRamble",1);
            String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
            log.info("腾讯云im删除用户聊天记录，返回结果：{}", result);
        }
    }

    public void deleteGroupContract(String groupId){
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.CLEAR_GROUP_MSG.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId",groupId);
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        log.info("腾讯云im删除群聊天记录，返回结果：{}", result);
        System.out.println(result);
    }

    public List<ImAppInfoVo> getAppInfo() {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiEnum.GET_APP_INFO.getUrl(), random);
        JSONObject jsonObject = new JSONObject();
        List<String> baseList = new ArrayList<>();
        baseList.add("Date");
        baseList.add("LoginUserNum");
        baseList.add("RegistUserNumOneDay");
        jsonObject.put("RequestField",baseList);
        String result = HttpClientUtil.doPostJsonObject(httpsUrl, jsonObject);
        Map map = JSON.parseObject(result, Map.class);
        List<ImAppInfoVo> imAppInfoVos = (List<ImAppInfoVo>) map.get("Result");
        System.out.println(imAppInfoVos);
        log.info("腾讯云im查询运营情况，返回结果：{}", result);
        return imAppInfoVos;
    }
}